package com.ysd.lis.service.qc.impl;

import java.util.List;

public class StandardDeviationCalculator {
    public static double calculatePopulationStdDev(List<Double> numbers) {
        if (numbers.isEmpty()) {
            throw new IllegalArgumentException("数据列表不能为空");
        }
        double avg = numbers.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0);
        double variance = numbers.stream()
                .mapToDouble(n -> Math.pow(n - avg, 2))
                .sum() / numbers.size();
        return Math.sqrt(variance);
    }

    // 样本标准差（除以n-1）
    public static double calculateSampleStdDev(List<Double> numbers) {
        if (numbers.size() <= 1) {
            throw new IllegalArgumentException("样本数量需大于1");
        }
        double avg = numbers.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0);
        double variance = numbers.stream()
                .mapToDouble(n -> Math.pow(n - avg, 2))
                .sum() / (numbers.size() - 1);
        return Math.sqrt(variance);
    }
}